<template>
  <div class="card">
    <dv-border-box-11 title="选题策划" :color="['#168BF9', '#112F7C']">
      <div class="content-wrapper">
        <!-- 环形图区域 - 并排显示 -->
        <div class="charts-row">
          <!-- 第一个环形图 - 重点选题 -->
          <div class="chart-item">
            <div class="chart-title">重点选题</div>
            <div class="chart-container">
              <div ref="chart1" class="chart"></div>
              <div class="chart-center-text">{{ totalKeyTopics }}</div>
              <div class="chart-center-subtext">总数</div>
            </div>
          </div>

          <!-- 第二个环形图 - 新闻线索 -->
          <div class="chart-item">
            <div class="chart-title">新闻线索</div>
            <div class="chart-container">
              <div ref="chart2" class="chart"></div>
              <div class="chart-center-text">{{ totalClues }}</div>
              <div class="chart-center-subtext">总数</div>
            </div>
          </div>
        </div>

        <!-- 表格区域 -->
        <div class="media-section">
          <div class="section-bg">
            <div class="media-header">
              <div class="chart-title">媒体报道</div>
              <div class="radio-container">
                <el-radio-group 
                  v-model="activeTab" 
                  @change="handleTabChange"
                  :disabled="tableLoading"
                >
                  <el-radio-button label="市宣选题"></el-radio-button>
                  <el-radio-button label="融媒体选题"></el-radio-button>
                </el-radio-group>
              </div>
            </div>
            <div class="content-container">
              <!-- 加载状态 -->
              <div v-if="tableLoading" class="loading-container">
                <div class="loading-spinner"></div>
                <div class="loading-text">数据加载中...</div>
              </div>
              
              <!-- 表格内容 -->
              <transition name="fade" mode="out-in">
                <div v-if="!tableLoading" class="table-container">
                  <el-table
                    :data="tableData"
                    style="width: 100%"
                    highlight-current-row
                    class="dark-blue-table"
                    :show-header="false"
                    :height="150"
                    @row-click="handleRowClick"
                  >
                    <el-table-column
                      prop="name"
                      label="标题"
                      min-width="150"
                      :show-overflow-tooltip="true"
                    >
                      <template slot-scope="scope">
                        <div class="title-cell">{{ scope.row.name }}</div>
                      </template>
                    </el-table-column>
                    <el-table-column
                      prop="createdOrganizationName"
                      label="账号"
                      width="150"
                      align="center"
                    >
                    </el-table-column>
                    <el-table-column
                      prop="date"
                      label="时间"
                      width="100"
                      align="center"
                    >
                    </el-table-column>
                  </el-table>
                </div>
              </transition>
            </div>
          </div>
        </div>
      </div>
    </dv-border-box-11>
  </div>
</template>

<script>
import * as echarts from "echarts";
import CardTitle from "../components/card-title.vue";
import { currentPOST } from "api/modules";
import { mapState } from "vuex";
export default {
  name: "ClueReport",
  components: {
    CardTitle,
  },
  data() {
    return {
      activeTab: "市宣选题",
      tableData: [],
      chart1: null,
      chart2: null,
      tableLoading: false, // 表格加载状态
      // 重点选题数据 - 初始化为空数组
      keyTopicsData: [],
      // 新闻线索数据 - 初始化为空数组
      cluesData: [],
      // 颜色配置 - 蓝绿黄
      colors: [
        {
          name: "蓝色",
          light: "#1890ff",
          dark: "#096dd9",
        },
        {
          name: "绿色",
          light: "#13c2c2",
          dark: "#08979c",
        },
        {
          name: "黄色",
          light: "#faad14",
          dark: "#d48806",
        },
        {
          name: "紫色",
          light: "#722ed1",
          dark: "#531dab",
        },
        {
          name: "红色",
          light: "#f5222d",
          dark: "#a8071a",
        },
      ],
    };
  },
  watch: {
    // 监听 lastDay 的变化，当变化时重新获取数据
    lastDay: {
      handler(newVal) {
        this.refreshData();
      },
      immediate: true, // 立即执行一次
    },
  },
  computed: {
    ...mapState(["lastDay"]),
    // 计算重点选题总数
    totalKeyTopics() {
      return this.keyTopicsData.reduce(
        (total, item) => total + Number(item.value),
        0
      );
    },
    // 计算新闻线索总数
    totalClues() {
      return this.cluesData.reduce(
        (total, item) => total + Number(item.value),
        0
      );
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getTopicPieData();
      this.getSubmitPieData();
      this.getArticleData(); // 初始化时加载表格数据
    });

    window.addEventListener("resize", this.handleResize);
  },
  beforeDestroy() {
    if (this.chart1) {
      this.chart1.dispose();
    }
    if (this.chart2) {
      this.chart2.dispose();
    }
    window.removeEventListener("resize", this.handleResize);
  },
  methods: {
    refreshData() {
      this.getTopicPieData();
      this.getSubmitPieData();
      this.getArticleData();
    },
    // Tab切换处理
    handleTabChange() {
      this.getArticleData(); // 切换tab时重新加载表格数据
    },
    // 重点选题pie请求
    getTopicPieData() {
      currentPOST("leftBottomPieTopicHome", { lastDay:  365 })
        .then((res) => {
          if (res.code === 0) {
            this.keyTopicsData = res.data || [];
            this.initKeyTopicsChart();
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("重点选题饼图请求失败:", error);
        });
    },

    // 新闻线索pie请求
    getSubmitPieData() {
      currentPOST("leftBottomPieSubmitHome", { lastDay:  365 })
        .then((res) => {
          if (res.code === 0) {
            this.cluesData = res.data || [];
            this.initCluesChart();
          } else {
            this.$Message({
              text: res.msg,
              type: "warning",
            });
          }
        })
        .catch((error) => {
          console.error("新闻线索饼图请求失败:", error);
        });
    },

    // 根据不同的Tab发送不同的请求
    async getArticleData() {
      this.tableLoading = true; // 开始加载
      
      try {
        let apiName = "leftBottomListmainHome"; // 默认接口
        
        if (this.activeTab === "融媒体选题") {
          apiName = "leftBottomListHome";
        }
        
        const res = await currentPOST(apiName, {
          lastDay: "365",
          pageSize: 100,
          current: 1,
          levels: [this.activeTab],
        });
        
        if (res.code === 0) {
          this.processTableData(res.data);
        } else {
          this.$Message({
            text: res.msg,
            type: "warning",
          });
        }
      } catch (error) {
        console.error("表格数据请求失败:", error);
        this.$Message({
          text: "数据加载失败",
          type: "error",
        });
      } finally {
        // 添加一个最小加载时间，让用户感受到切换效果
        setTimeout(() => {
          this.tableLoading = false;
        }, 300);
      }
    },
    
    // 处理媒体报道数据
    processTableData(responseData) {
      if (
        !responseData ||
        !responseData.data ||
        !Array.isArray(responseData.data)
      ) {
        console.warn("媒体报道数据格式不正确");
        this.tableData = [];
        return;
      }

      const articles = responseData.data;

      // 将接口数据映射为表格需要的格式
      this.tableData = articles.map((article) => {
        const releaseTime = this.formatDate(article.createdTime);
        
        return {
          name: article.name || "--",
          createdOrganizationName: article.createdOrganizationName || "--",
          date: releaseTime || "--",
          run: article.run,
          grade: article.grade,
        };
      });
    },
    
    // 格式化日期，去掉时间部分
    formatDate(dateString) {
      if (!dateString) return "--";
      return dateString.split(" ")[0];
    },

    // 初始化重点选题环形图
    initKeyTopicsChart() {
      if (!this.$refs.chart1 || !this.keyTopicsData.length) return;

      this.chart1 = echarts.init(this.$refs.chart1);

      const chartData = this.keyTopicsData.map((item, index) => ({
        value: Number(item.value),
        name: item.type,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: this.colors[index % this.colors.length].light },
            { offset: 1, color: this.colors[index % this.colors.length].dark },
          ]),
        },
      }));

      const option1 = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        series: [
          {
            name: "重点选题",
            type: "pie",
            radius: ["50%", "75%"],
            center: ["50%", "50%"],
            avoidLabelOverlap: true,
            itemStyle: {
              borderColor: "#0a2c5e",
              borderWidth: 2,
            },
            label: {
              show: true,
              position: "outside",
              formatter: "{b}\n{c}",
              color: "#bae7ff",
              fontSize: 10,
              fontWeight: "normal",
              align: "center",
              lineHeight: 16,
            },
            labelLine: {
              show: true,
              length: 3,
              length2: 3,
              smooth: true,
              lineStyle: {
                color: "rgba(186, 231, 255, 0.6)",
                width: 1,
              },
            },
            emphasis: {
              scale: false,
              focus: "self",
              label: {
                show: true,
                fontSize: 12,
                fontWeight: "bold",
                color: "#ffffff",
              },
            },
            data: chartData,
          },
        ],
      };
      this.chart1.setOption(option1);
    },

    // 初始化新闻线索环形图
    initCluesChart() {
      if (!this.$refs.chart2 || !this.cluesData.length) return;

      this.chart2 = echarts.init(this.$refs.chart2);

      const chartData = this.cluesData.map((item, index) => ({
        value: Number(item.value),
        name: item.type,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: this.colors[index % this.colors.length].light },
            { offset: 1, color: this.colors[index % this.colors.length].dark },
          ]),
        },
      }));

      const option2 = {
        tooltip: {
          trigger: "item",
          formatter: "{a} <br/>{b}: {c} ({d}%)",
        },
        series: [
          {
            name: "新闻线索",
            type: "pie",
            radius: ["50%", "75%"],
            center: ["50%", "50%"],
            avoidLabelOverlap: true,
            itemStyle: {
              borderColor: "#0a2c5e",
              borderWidth: 2,
            },
            label: {
              show: true,
              position: "outside",
              formatter: "{b}\n{c}",
              color: "#bae7ff",
              fontSize: 10,
              fontWeight: "normal",
              align: "center",
              lineHeight: 16,
            },
            labelLine: {
              show: true,
              length: 8,
              length2: 8,
              smooth: true,
              lineStyle: {
                color: "rgba(186, 231, 255, 0.6)",
                width: 1,
              },
            },
            emphasis: {
              scale: false,
              focus: "self",
              label: {
                show: true,
                fontSize: 12,
                fontWeight: "bold",
                color: "#ffffff",
              },
            },
            data: chartData,
          },
        ],
      };
      this.chart2.setOption(option2);
    },

    // 处理窗口大小变化
    handleResize() {
      if (this.chart1) {
        this.chart1.resize();
      }
      if (this.chart2) {
        this.chart2.resize();
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.card {
  margin-top: 30px;
  height: 450px;
  display: flex;
  justify-content: center;
}

.content-wrapper {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 20px;
  padding-top: 60px;
  box-sizing: border-box;
}

// 环形图区域 - 并排显示
.charts-row {
  width: 100%;
  height: 45%;
  display: flex;
  justify-content: space-around;
  align-items: center;

  .chart-item {
    text-align: center;
    width: 45%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .chart-title {
      color: #bae7ff;
      font-size: 16px;
      font-weight: 500;
      height: 10px;
    }

    .chart-container {
      position: relative;
      width: 100%;
      height: calc(100% - 30px);
      display: flex;
      align-items: center;
      justify-content: center;

      .chart {
        width: 100%;
        height: 110px;
      }

      .chart-center-text {
        position: absolute;
        top: 45%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #ffffff;
        font-size: 24px;
        font-weight: bold;
        text-shadow: 0 0 10px rgba(24, 144, 255, 0.8);
      }

      .chart-center-subtext {
        position: absolute;
        top: 60%;
        left: 50%;
        transform: translate(-50%, -50%);
        color: #bae7ff;
        font-size: 12px;
      }
    }
  }
}

.media-section {
  height: calc(100% - 235px);
}

.section-bg {
  border-radius: 8px;
  padding: 15px;
  height: 90%;
  position: relative;
  display: flex;
  flex-direction: column;
}

.media-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  flex-shrink: 0;
}

.radio-container {
  display: flex;
  flex-shrink: 0;
}

// 加载状态样式
.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 150px;
  
  .loading-spinner {
    width: 30px;
    height: 30px;
    border: 3px solid rgba(24, 144, 255, 0.3);
    border-top: 3px solid #1890ff;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 10px;
  }
  
  .loading-text {
    color: #bae7ff;
    font-size: 14px;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

// 过渡动画
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.3s ease;
}

.fade-enter, .fade-leave-to {
  opacity: 0;
}

// 标题单元格样式
.title-cell {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
  cursor: pointer;
}

.table-container {
  flex: 1;
  position: relative;
  min-height: 0;
  overflow: hidden;
}

::v-deep .el-radio-group {
  .el-radio-button {
    .el-radio-button__inner {
      background: linear-gradient(135deg, #1a3a5f 0%, #2d5278 100%);
      color: #bae7ff;
      border: 1px solid #2d5278;
      font-size: 14px;
      font-weight: 500;
      padding: 8px 16px;
      transition: all 0.3s ease;

      &:hover {
        color: #ffffff;
        background: linear-gradient(135deg, #2d5278 0%, #3a6ea5 100%);
      }
    }

    &.is-active {
      .el-radio-button__inner {
        background: linear-gradient(135deg, #1890ff 0%, #096dd9 100%);
        color: #ffffff;
        border-color: #1890ff;
        box-shadow: 0 0 8px rgba(24, 144, 255, 0.5);
      }
    }
    
    // 禁用状态
    &.is-disabled {
      .el-radio-button__inner {
        opacity: 0.6;
        cursor: not-allowed;
      }
    }
  }
}

.chart-title {
  color: #bae7ff;
  font-size: 16px;
  font-weight: 500;
  margin-block: 10px;
  flex-shrink: 0;
}
</style>